//
//  AppDelegate+Location.m
//  kuaile
//
//  Created by liujingyi on 15/10/13.
//  Copyright © 2015年 ttouch. All rights reserved.
//

#import "AppDelegate+Location.h"
#import <MapKit/MapKit.h>

#define IOS8after [[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0

@interface AppDelegate ()<CLLocationManagerDelegate>
@end

@implementation AppDelegate (Location)

- (void)startLocation {
    self.locationManager                 = [[CLLocationManager alloc] init];
    self.locationManager.delegate        = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
//    self.locationManager.distanceFilter  = 5.0f;
    self.locationManager.distanceFilter = kCLDistanceFilterNone;
    [self.locationManager startUpdatingLocation];
    
    if (IOS8after) {
        [self.locationManager requestWhenInUseAuthorization];
    }
}

#pragma mark - CLLocationManagerDelegate
// 地理位置发生改变时触发
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    [manager stopUpdatingLocation];
    
    AppDelegate *appdelegate = kAppDelegate;
    
    appdelegate.publicProperty.loactionModel = [[YKLoactionModel alloc] init];
    appdelegate.publicProperty.loactionModel.lat = [NSString stringWithFormat:@"%f" , newLocation.coordinate.latitude];
    appdelegate.publicProperty.loactionModel.lng = [NSString stringWithFormat:@"%f" , newLocation.coordinate.longitude];
    
    CLGeocoder *clGeoCoder = [[CLGeocoder alloc] init];
    [clGeoCoder reverseGeocodeLocation:newLocation completionHandler: ^(NSArray *placemarks,NSError *error) {
        for (CLPlacemark *placeMark in placemarks)
        {
            NSDictionary *addressDic=placeMark.addressDictionary;
            
            appdelegate.publicProperty.loactionModel.state = [addressDic objectForKey:@"State"];
            appdelegate.publicProperty.loactionModel.city = [addressDic objectForKey:@"City"];
            appdelegate.publicProperty.loactionModel.subLocality = [addressDic objectForKey:@"SubLocality"];
            appdelegate.publicProperty.loactionModel.street = [addressDic objectForKey:@"Street"];
            
            appdelegate.publicProperty.loactionModel.address = [NSString stringWithFormat:@"%@%@%@%@" , [addressDic objectForKey:@"State"] , [addressDic objectForKey:@"City"] ,[addressDic objectForKey:@"SubLocality"] , [addressDic objectForKey:@"Street"]];
            
        }  
        
    }];
}

// 定位失误时触发
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"定位失败, 错误: %@",error);
}

@end
